'use strict';
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  const db = uniCloud.database();

  let body = event;
  if (typeof event.body === 'string') {
    try {
      body = JSON.parse(event.body);
    } catch (err) {
      return {
        code: -1,
        msg: '请求体 JSON 格式错误',
        error: err.message
      };
    }
  }

  try {
    // 参数校验
    if (!body.day) {
      return {
        code: -2,
        msg: "缺少必要参数: day",
      };
    }

    if (!body.appointedSlot) {
      return {
        code: -2,
        msg: "缺少必要参数: appointedSlot",
      };
    }

    const { day, appointedSlot } = body;

    // 验证用户身份
    const uniIDIns = uniID.createInstance({ context });
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
      return { code: 403, msg: "用户身份验证失败" };
    }

    // 删除匹配记录（uid + day + appointedSlot）
    const res = await db.collection('appoint_schedule')
      .where({
        uid: uid,
        day: day,
        appointedSlot: appointedSlot
      })
      .remove();

    return {
      code: 0,
      message: '指定时间段的记录已删除',
      deletedCount: res.deleted
    };

  } catch (error) {
    console.error("Error in deleting appointed slot:", error);
    return {
      code: -5,
      message: '取消失败',
      error: error.message
    };
  }
};
